<template>
  <el-form
    :model="form"
    ref="createForm"
    :rules="rules"
    class="form mp-form"
    label-width="100px"
  >
    <el-form-item label="页面编码" prop="page_code">
      <el-input v-model="form.page_code" autocomplete="off" :disabled="isView"></el-input>
    </el-form-item>
    <el-form-item label="页面名称" prop="page_name">
      <el-input v-model="form.page_name" autocomplete="off" :disabled="isView"></el-input>
    </el-form-item>
    <el-form-item label="页面路由路径" prop="url">
      <el-input v-model="form.url" autocomplete="off" :disabled="isView"></el-input>
    </el-form-item>
    <el-form-item label="页面介绍" prop="page_desc">
      <el-input v-model="form.page_desc" type="textarea" :rows="2" autocomplete="off" :disabled="isView"></el-input>
    </el-form-item>
    <el-form-item v-if="isView" label-width="0" class="form-item-center">
      <el-button type="primary" @click="handleCancel()" size="default">确 定</el-button>
    </el-form-item>
    <el-form-item v-else label-width="0" class="form-item-center">
      <el-button type="primary" @click="handleSave()" size="large">确 定</el-button>
      <el-button @click="handleCancel()" size="large">取 消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import _ from 'lodash';

const props = defineProps({
  currentData: Object,
  appId: [String, Number],
  isView: Boolean
});

const DFT_FORM = {
  type: 4,
  page_code: '',
  page_name: '',
  page_desc: '',
  url: ''
};

const loading = ref(false);
const form = ref(_.cloneDeep(DFT_FORM));
const rules = {
  page_code: [
    { required: true, message: '请输入页面编码', trigger: 'blur' }
  ],
  page_name: [
    { required: true, message: '请输入页面名称', trigger: 'blur' }
  ]
};

const init = () => {
  let formValue = null;

  if (props.currentData && props.currentData.page_id) {
    formValue = _.cloneDeep(props.currentData);
  } else {
    formValue = _.defaults({
      page_code: $utils.getNanoid(),
      app_id: props.appId
    }, DFT_FORM);
  }

  form.value = formValue;
};

const handleSave = async () => {
  loading.value = true;

  const ret = await $japi.page.pageUpsert(form.value);

  if (ret) {
    $message('操作成功！');
    emit('success', ret);
  }

  loading.value = false;
};

const handleCancel = () => {
  emit('cancel');
};

const emit = defineEmits(['success', 'cancel']);

onMounted(() => {
  init();
});

watch(() => props.currentData, () => {
  init();
}, { deep: true });
</script>
